home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 1 / Cream of the Crop 1.iso / PROGRAM / SNIP1292.ARJ / WB_FCOPY.C < prev    next >
C/C++ Source or Header  |  1992-07-03  |  2KB  |  68 lines

  1. /* 
  2. ** by: Walter Bright via Usenet C newsgroup
  3. **
  4. ** modified by: Bob Stout based on a recommendation by Ray Gardner
  5. **
  6. ** modified by: David Gersic to deal with binary files
  7. **
  8. ** There is no point in going to asm to get high speed file copies. Since it
  9. ** is inherently disk-bound, there is no sense (unless tiny code size is
  10. ** the goal). Here's a C version that you'll find is as fast as any asm code
  11. ** for files larger than a few bytes (the trick is to use large disk buffers):
  12. */
  13.  
  14.  
  15. #if Afilecopy
  16. int file_copy(from,to)
  17. #else
  18. int file_append(from,to)
  19. #endif
  20. char *from,*to;
  21. {       int fdfrom,fdto;
  22.         int bufsiz;
  23.  
  24.         fdfrom = open(from,O_RDONLY|O_BINARY,0);
  25.         if (fdfrom < 0)
  26.                 return 1;
  27. #if Afileappe
  28.         /* Open R/W by owner, R by everyone else        */
  29.         fdto=open(to,O_BINARY|O_CREAT|O_APPEND|O_RDWR,S_IREAD|S_IWRITE);
  30.         if (fdto < 0)
  31.             goto err;
  32. #else
  33.         fdto=open(to,O_BINARY|O_CREAT|O_TRUNC|O_RDWR,S_IREAD|S_IWRITE);
  34.         if (fdto < 0)
  35.             goto err;
  36. #endif
  37.  
  38.         /* Use the largest buffer we can get    */
  39.         for (bufsiz = 0x4000; bufsiz >= 128; bufsiz >>= 1)
  40.         {   register char *buffer;
  41.  
  42.             buffer = (char *) malloc(bufsiz);
  43.             if (buffer)
  44.             {   while (1)
  45.                 {   register int n;
  46.  
  47.                     n = read(fdfrom,buffer,bufsiz);
  48.                     if (n == -1)                /* if error             */
  49.                         break;
  50.                     if (n == 0)                 /* if end of file       */
  51.                     {   free(buffer);
  52.                         close(fdto);
  53.                         close(fdfrom);
  54.                         return 0;               /* success              */
  55.                     }
  56.                     if (n != write(fdto,buffer,(unsigned) n))
  57.                         break;
  58.                 }
  59.                 free(buffer);
  60.                 break;
  61.             }
  62.         }
  63. err2:   close(fdto);
  64.         remove(to);                             /* delete any partial file */
  65. err:    close(fdfrom);
  66.         return 1;
  67. }
  68.